package xyz.archknight.app.loginput.dictionary.gen.ui

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.swing.Swing
import xyz.archknight.app.loginput.dictionary.gen.bean.Packet
import xyz.archknight.app.loginput.dictionary.gen.bean.StatusProtocol
import xyz.archknight.app.loginput.dictionary.gen.service.EventBus
import java.awt.EventQueue
import java.awt.GridBagConstraints
import java.awt.GridBagLayout
import java.awt.Insets
import javax.swing.JLabel
import javax.swing.JPanel

/**
 * 状态栏
 *
 * @author midnite
 * create at 2020-06-17 6:41 上午
 */
class StatusBar() : JPanel() {
    private val panelLayout = GridBagLayout()
    private val constraints = GridBagConstraints()
    private val mainStorageState = JLabel()
    private val cacheState = JLabel()

    init {
        EventBus.status.subscribe(this::refreshStatusRoute)
        createUI()
    }

    private fun createUI() {
        layout = panelLayout

        constraints.fill = GridBagConstraints.BOTH
        constraints.weightx = 0.5
        constraints.gridwidth = 1
        constraints.anchor = GridBagConstraints.WEST
        constraints.insets = Insets(4, 4, 4, 4)
        panelLayout.setConstraints(mainStorageState, constraints)
        updateMainStorage(0)
        add(mainStorageState)

        panelLayout.setConstraints(cacheState, constraints)
        updateCache(0)
        add(cacheState)
    }

    private fun refreshStatusRoute(packet: Packet<StatusProtocol, Long>) {
        when(packet.action) {
            StatusProtocol.Loading -> loading()
            StatusProtocol.Main -> updateMainStorage(packet.payload)
            StatusProtocol.Cache -> updateCache(packet.payload)
        }
    }

    private fun loading() {
        mainStorageState.text = "正在读取数据库文件，请稍候……"
    }

    private fun updateMainStorage(n: Long = 0L) = GlobalScope.launch(Dispatchers.Swing) {
        mainStorageState.text = "主词库中有 $n 条词汇"
    }

    private fun updateCache(n: Long = 0L) = GlobalScope.launch(Dispatchers.Swing) { cacheState.text = "缓存区有 $n 条词汇" }
}